import React, { useCallback } from 'react'
import { Table, Space, Button, Popconfirm, message, Tag, Drawer, Form, Input, Select, Tree } from 'antd'
import { useState } from 'react'
import { useEffect } from 'react'
import { getAdminList, addAdmin, deleteAdmin } from './../../api/user.js'
import routes from './../../router/menu.js'
import './Admin.css'
const { Option } = Select

const App = () => {
    const [form] = Form.useForm()
    const columns = [
        {
            align: 'center',
            title: '序号',
            width: 60,
            key: 'num',
            render (text, data, index) {
              return (<span>{pageNum * pageize + index+1}</span>)
            }
        },
        {
            title: '管理员账号',
            dataIndex: 'adminname',
        },
        {
            title: '角色',
            dataIndex: 'role',
            render (text, data, index) {
                return (<>{text === 1 ? <Tag color="green">管理员</Tag> : <Tag color="purple">超级管理员</Tag> }</>)
            }
        },
        {
            align: 'center',
            title: '操作',
            width: 220,
            key: 'do',
            fixed: 'right',
            render (text, data, index) { // 删除管理员
              return (
                <>
                  <Space>
                        <Button>编辑</Button>
                        <Popconfirm placement="top" title="确认删除吗？" onConfirm={() => {
                                deleteAdmin({
                                    adminid: data.adminid
                                }).then(res => {
                                    getAdminList().then( res => {
                                        setAdminList(res.data)
                                    })
                                })
                            }} okText="确定" cancelText="取消">
                            <Button>删除</Button>
                      </Popconfirm>
                  </Space>
                </>
              )
            }
          },
    ]
    const [ adminList, setAdminList ] = useState([])
    const [ pageNum, setPageNum ] = useState(0)
    const [ pageize, setPageize ] = useState(10)
    const [ visible, setVisible ] = useState(false)
    const [ selectedKeys, setSelectedKeys ] = useState(['0-0'])
    const [ role, setRole ] = useState(1)
    const [ adminname, setAdminname ] = useState('')
    const [ password, setPassword ] = useState('')
    const [ selectData, setSelectData ] = useState([])


    useEffect(() => {
        getAdminList().then(res => {
            setAdminList(res.data)
        })
    }, [])
    // 页面改变
    const pageChange = (pagination, filters, sorter) => {
        setPageNum(pagination.current - 1)
        setPageize(pagination.pageSize)
    }
    // 关闭侧边添加管理员
    const onClose = () => {
        setVisible(false)
    }
    // 打开侧边添加管理员结构
    const addAdminFn = () => {
        setVisible(true)
    }
    // 修改role管理员权限值
    const handleChange = val => {
        setRole(val)
    }
    // 修改管理员查看树结构权限
    const onCheck = (selectedKeys,val , e) => {
        // console.log(selectedKeys);
        setSelectData([...selectedKeys, ...val.halfCheckedKeys])  // selectedKeys 全部选中的子元素父元素 val.halfCheckedKeys子元素未全选的父元素 组合到一起 这样就不需要另行处理
        setSelectedKeys(selectedKeys)
    }
    // 提交
    const submit = useCallback(() => {
        // console.log(adminname, password, role, selectedKeys);
        const data = {adminname, password, role, checkedKeys: selectData}
        addAdmin(data).then(res => {
            if (res.code === '10004') {
                message.error('该管理员已存在')
            } else {
                // 将受控组件的数据调整为初始数据
                setAdminname('')
                setPassword('')
                setRole(1)
                setSelectedKeys(['0-0'])
                form.resetFields()  // 清空表单内的数据 1需要在函数组件内从Form引入 2form绑定到Form表单 3利用form和API来清空表单
                setVisible(false)
                getAdminList().then( res => {
                    setAdminList(res.data)
                })
            }
        })
    }, [adminname, password, role, selectData, form])
    const adminnameChange = (e) => {
        setAdminname(e.target.value)
    }
    const passwordChange = (e) => {
        setPassword(e.target.value)
    }
    return (
        <>
            <Space style={{marginBottom: '10px'}}>
                <Button type="primary" onClick={addAdminFn}>添加管理员</Button>
            </Space>
            <Table rowKey="adminid" columns={columns} width="100%" onChange={pageChange} dataSource={adminList} scroll={{ x: 100, y: 580  }} />
            <Drawer
                className="myself"
                title="添加管理员"
                placement="right"
                closable={true}
                onClose={onClose}
                visible={visible}
                key="right"
                width='500px'
                >
                    <Form
                    form={form}
                    name="basic"
                    initialValues={{ remember: true }}
                    // onFinish={onFinish}
                    // onFinishFailed={onFinishFailed}
                    autoComplete="off"
                    onFinish={(values) => {console.log(values)}}
                    >
                        <Form.Item
                            label="账号"
                            name="username"
                            rules={[{ required: true, message: '管理员账号' }]}
                        >
                            <Input value={adminname} onChange={adminnameChange} />
                        </Form.Item>

                        <Form.Item
                            label="密码"
                            name="password"
                            rules={[{ required: true, message: '管理员密码' }]}
                        >
                            <Input.Password onChange={passwordChange} value={password} />
                        </Form.Item>

                        <Select defaultValue="1" value={role} style={{ width: 350, marginBottom: '15px' }} onChange={handleChange}>
                            <Option value="1">管理员</Option>
                            <Option value="2">超级管理员</Option>
                        </Select>

                        <Tree
                            checkable
                            checkedKeys={selectedKeys}
                            autoExpandParent="true" // 自动展开父节点
                            treeData={routes} // 树数据
                            onCheck={onCheck}
                            />

                        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                            <Button type="primary" htmlType="submit" onClick={submit}>
                            提交管理员信息
                            </Button>
                        </Form.Item>
                    </Form>
                </Drawer>
        </>
    )
}

export default App